package com.globallogic.dailyplanner.jsfbeans;

import java.io.Serializable;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

import javax.faces.application.FacesMessage;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.SessionScoped;
import javax.faces.context.FacesContext;
import javax.faces.event.ActionEvent;

import org.primefaces.event.ScheduleEntryMoveEvent;
import org.primefaces.event.ScheduleEntryResizeEvent;
import org.primefaces.event.SelectEvent;
import org.primefaces.model.DefaultScheduleModel;
import org.primefaces.model.ScheduleEvent;
import org.primefaces.model.ScheduleModel;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;

import com.globallogic.dailyplanner.dto.DailyPlan;
import com.globallogic.dailyplanner.dto.User;
import com.globallogic.dailyplanner.service.DailyPlanService;
import com.globallogic.dailyplanner.service.LoginService;
import com.globallogic.dailyplanner.service.UserService;
import com.globallogic.dailyplanner.utils.MyScheduleEvent;
import com.globallogic.dailyplanner.utils.TodoBeanUtil;

@Controller
@ManagedBean
@SessionScoped
public class TodoBean implements Serializable {
	private static final long serialVersionUID = 6360163180434938382L;

	@Autowired
	private DailyPlanService dpServise;
	@Autowired
	private UserService userService;
	@Autowired
	private LoginService loginService;
	private ScheduleModel eventModel;
	private ScheduleEvent event = new MyScheduleEvent();
	private int OldEventID;

	public void init() {
		if (!FacesContext.getCurrentInstance().isPostback()) {
			eventModel = new DefaultScheduleModel();
			String userName = loginService.getAuthUsername();
			User authUser = userService.findOneByName(userName);

			List<DailyPlan> dailyPlans = dpServise.getAllById(authUser.getId());
			if (dailyPlans != null) {
				for (DailyPlan dp : dailyPlans) {
					eventModel.addEvent(new MyScheduleEvent(
											dp.getActivity(),
											dp.getCalendar().getTime(),
											TodoBeanUtil
											.getEndDate(dp),
											TodoBeanUtil
											.getActualDate(dp),
											dp.getComment()));
				}
			}
		}
	}

	public ScheduleModel getEventModel() {
		return eventModel;
	}

	public ScheduleEvent getEvent() {
		return event;
	}

	public void setEvent(ScheduleEvent event) {
		this.event = event;
	}

	public void addEvent(ActionEvent actionEvent) {
		User user = userService.findOneByName(loginService.getAuthUsername());

		Calendar cal = Calendar.getInstance();
		cal.setTime(event.getStartDate());
		if (event.getId() == null) {
			eventModel.addEvent(event);
			dpServise.save(TodoBeanUtil.createDailyPlan(
							user,
							cal,
							event.getTitle(),
							TodoBeanUtil.getEstimDuration(event),
							TodoBeanUtil.getActualDuration((MyScheduleEvent) event),
							((MyScheduleEvent) event).getComment()));
		} else {
			dpServise.delete(OldEventID);
			dpServise.save(TodoBeanUtil.createDailyPlan(
							user,
							cal,
							event.getTitle(),
							TodoBeanUtil.getEstimDuration(event),
							TodoBeanUtil.getActualDuration((MyScheduleEvent) event),
							((MyScheduleEvent) event).getComment()));
			eventModel.updateEvent(event);
		}

		event = new MyScheduleEvent();
	}

	public void deleteEvent(ActionEvent actionEvent) {
		if (event.getStartDate().after(TodoBeanUtil.getTodayMorningDate())) {
			dpServise.delete(OldEventID);
			eventModel.deleteEvent(event);
		} else {
			FacesMessage message = new FacesMessage(FacesMessage.SEVERITY_WARN,
					"Event can't be deleted", "you can delete totay and future events only.");

			addMessage(message);
		}
	}

	private Integer getDailyPlanIdByEvent(ScheduleEvent event) {
		List<DailyPlan> dailyPlans = dpServise.getAll();
		if (dailyPlans != null) {
			for (DailyPlan dp : dailyPlans) {
				if (dp.getActivity().equals(event.getTitle())
						&& dp.getCalendar().getTime()
								.compareTo(event.getStartDate()) == 0
						&& dp.getEstimateDuration().equals(
								TodoBeanUtil.getEstimDuration(event))) {
					return dp.getId();
				}
			}
		}
		return null;
	}

	public void onEventSelect(SelectEvent selectEvent) {
		event = (MyScheduleEvent) selectEvent.getObject();
		OldEventID = getDailyPlanIdByEvent(event);
	}

	public void onDateSelect(SelectEvent selectEvent) {
		event = new MyScheduleEvent("", (Date) selectEvent.getObject(),
				(Date) selectEvent.getObject(), (Date) selectEvent.getObject(),
				"");
	}

	public void onEventMove(ScheduleEntryMoveEvent event) {
		User user = userService.findOneByName(loginService.getAuthUsername());
		MyScheduleEvent myEvent = (MyScheduleEvent)event.getScheduleEvent();
		
		String  title = myEvent.getTitle();
		Date startDate = myEvent.getStartDate();
		Date endDate = myEvent.getEndDate();
		String comment = myEvent.getComment();
		
		Calendar calendarStart = Calendar.getInstance();
		calendarStart.setTime(startDate);
		calendarStart.add(Calendar.DAY_OF_MONTH, -event.getDayDelta());
		calendarStart.add(Calendar.MINUTE, -event.getMinuteDelta());
		
		Calendar calendarEnd = Calendar.getInstance();
		calendarEnd.setTime(endDate);
		calendarEnd.add(Calendar.DAY_OF_MONTH, -event.getDayDelta());
		calendarEnd.add(Calendar.MINUTE, -event.getMinuteDelta());
		
		ScheduleEvent temp = new MyScheduleEvent(title, calendarStart.getTime(), calendarEnd.getTime());
		int id = getDailyPlanIdByEvent(temp);
		
		calendarStart.setTime(startDate);
		
		dpServise.delete(id);
		dpServise.save(TodoBeanUtil.createDailyPlan(user,
									calendarStart,
									title,
									TodoBeanUtil.getEstimDuration(myEvent),
									TodoBeanUtil.getActualDuration(myEvent),
									comment));
		
		FacesMessage message = new FacesMessage(FacesMessage.SEVERITY_INFO,
				"Event moved", "Day delta:" + event.getDayDelta()
						+ ", Minute delta:" + event.getMinuteDelta());

		addMessage(message);
	}

	public void onEventResize(ScheduleEntryResizeEvent event) {
		User user = userService.findOneByName(loginService.getAuthUsername());
		MyScheduleEvent myEvent = (MyScheduleEvent)event.getScheduleEvent();
		
		String  title = myEvent.getTitle();
		Date startDate = myEvent.getStartDate();
		Date endDate = myEvent.getEndDate();
		String comment = myEvent.getComment();
		
		Calendar calendarStart = Calendar.getInstance();
		
		Calendar calendarEnd = Calendar.getInstance();
		calendarEnd.setTime(endDate);
		calendarEnd.add(Calendar.DAY_OF_MONTH, -event.getDayDelta());
		calendarEnd.add(Calendar.MINUTE, -event.getMinuteDelta());
		
		ScheduleEvent temp = new MyScheduleEvent(title, startDate, calendarEnd.getTime());

		int id = getDailyPlanIdByEvent(temp);
		
		calendarStart.setTime(startDate);
		
		dpServise.delete(id);
		dpServise.save(TodoBeanUtil.createDailyPlan(user,
									calendarStart,
									title,
									TodoBeanUtil.getEstimDuration(myEvent),
									TodoBeanUtil.getActualDuration(myEvent),
									comment));
		
		FacesMessage message = new FacesMessage(FacesMessage.SEVERITY_INFO,
				"Event resized", "Day delta:" + event.getDayDelta()
						+ ", Minute delta:" + event.getMinuteDelta());

		addMessage(message);
	}

	private void addMessage(FacesMessage message) {
		FacesContext.getCurrentInstance().addMessage(null, message);
	}
}